package com.qing.springcloud.manger;


import com.qing.springcloud.model.ChatMessage;
import com.qing.springcloud.model.MsgType;
import com.qing.springcloud.model.UserStatus;
import com.qing.springcloud.service.FriendService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class UserChannelManager {

    private static final AttributeKey<Long> USER_ID_ATTRIBUTE = AttributeKey.valueOf("userId");
    private final Map<Long, Channel> userChannelMap = new ConcurrentHashMap<>();
    private final Map<Long, UserStatus> userStatusMap = new ConcurrentHashMap<>();

    @Autowired
    private FriendService friendService;
    public void bindUserToChannel(Long userId, Channel channel) {
        channel.attr(USER_ID_ATTRIBUTE).set(userId);
        userChannelMap.put(userId, channel);
        userStatusMap.put(userId, UserStatus.ONLINE);
    }

    public Long getUserId(Channel channel) {
        return channel.attr(USER_ID_ATTRIBUTE).get();
    }

    public Channel getChannel(Long userId) {
        return userChannelMap.get(userId);
    }

    public void addChannel(Channel channel) {
        // 等待认证后绑定用户
    }

    public void removeChannel(Long userId) {
        userChannelMap.remove(userId);
        userStatusMap.put(userId, UserStatus.OFFLINE);
    }

    public void updateUserStatus(Long userId, UserStatus status) {
        userStatusMap.put(userId, status);
        // 通知好友用户状态变更
        notifyFriendsStatusChange(userId, status);
    }

    public UserStatus getUserStatus(Long userId) {
        return userStatusMap.getOrDefault(userId, UserStatus.OFFLINE);
    }

    public void removeChannel(Channel channel) {
        Long userId = getUserId(channel);
        if (userId != null) {
            removeChannel(userId);
        }
    }

    private void notifyFriendsStatusChange(Long userId, UserStatus status) {
        List<Long> friendIds = friendService.getFriendIds(userId);
        for (Long friendId : friendIds) {
            Channel friendChannel = getChannel(friendId);
            if (friendChannel != null && friendChannel.isActive()) {
                ChatMessage statusMsg = new ChatMessage();
                statusMsg.setMsgType(MsgType.STATUS);
                statusMsg.setSenderId(userId);
                statusMsg.setContent(status.name());
                friendChannel.writeAndFlush(new TextWebSocketFrame(statusMsg.toJson()));
            }
        }
    }
}
